<?php

namespace App\Console\Commands;

use App\Library\Logic\InviteLogic;
use App\Library\Logic\SalesRecordLogic;
use App\Library\Logic\ShopOrderLogic;
use Illuminate\Console\Command;

class InviteSettlementCommand extends Command
{
    /**
     * 给邀请人佣金
     *
     * @var string
     */
    protected $signature = 'command:inviteSettlement {serialNumber}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        $serialNumber = $this->argument('serialNumber');
        if (empty($serialNumber) || strlen($serialNumber) !== 20) return;
        $order = ShopOrderLogic::findBySerialNumber($serialNumber);
        if (is_null($order)) return;
        $salesRecord = SalesRecordLogic::getByWhere([
            'type' => 'invite',
            'objectType' => 'shop_order',
            'object_id' => $order->order_id,
            'inviteFlag' => 0
        ]);
        if (is_null($salesRecord)) return;

        foreach ($salesRecord as $item) {
            $invite = InviteLogic::findByWhere(['inviterId' => $item->to_user_id, 'inviteeId' => $item->from_user_id]);
            if (is_null($invite)) return;
            $invite->commission += $item->amount;
            $invite->order_count += 1;
            $invite->save();

            $item->invite_flag = 1;
            $item->save();
        }
    }
}
